import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';

import '../../utils/http.dart';
import '../../utils/toast.dart';
import '../../utils/validate.dart';

class HouseForm extends StatefulWidget {
  const HouseForm({super.key, required this.params});
  final Map<String, dynamic> params;
  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  // late Map<String, dynamic> _formData;
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _mobileController = TextEditingController();
  var logger = Logger();
   Map _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };

  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        showBottomSheet(tag);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.add, size: 30, color: Color.fromARGB(255, 85, 145, 175)),
          Text(
            '上传人像面照片',
            style: TextStyle(color: Color.fromARGB(255, 85, 145, 175)),
          ),
        ],
      ),
    );
  }

  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width - 20,
          height: 300,
          child: Image.network(photoUrl, fit: BoxFit.contain),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: GestureDetector(
            child: const Icon(Icons.delete, color: Colors.red),
            onTap: () {
              setState(() {
                _formData[tag] = '';
              });
            },
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   // logger.i(widget.params['id']);
   // print(widget.params);

    // 合并传入参数
    _formData = {
      'point': widget.params['point'] ?? '',
      'building': widget.params['building'] ?? '',
      'room': widget.params['room'] ?? '',
      'gender': widget.params['gender'] ?? 1,
      'name': widget.params['name'] ?? '',
      'mobile': widget.params['mobile'] ?? '',
      'idcardFrontUrl': widget.params['idcardFrontUrl'] ?? '',
      'idcardBackUrl': widget.params['idcardBackUrl'] ?? '',
    };


    // 初始化控制器
    _nameController.text = _formData['name'] ?? '';
    _mobileController.text = _formData['mobile'] ?? '';



  }


  void showBottomSheet(String tag) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(10),
          height: 180,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  // 调用相机
                  ImagePicker picker = ImagePicker();
                  final XFile? photo = await picker.pickImage(
                    source: ImageSource.camera,
                  );
                  if (photo != null) {
                    // 读取文件字节
                    final bytes = await photo.readAsBytes();

                    // 创建FormData，使用bytes而不是File
                    FormData formData = FormData.fromMap({
                      //
                      "file": MultipartFile.fromBytes(
                        bytes,
                        filename: photo.name, // 设置文件名
                      ),
                    });
                    uploadAvatar(tag, formData);
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.image),
                title: const Text('相册'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  // 调用相册
                  ImagePicker picker = ImagePicker();
                  final XFile? image = await picker.pickImage(
                    source: ImageSource.gallery,
                  );
                  if (image != null) {
                    // 读取文件字节
                    final bytes = await image.readAsBytes();

                    // 创建FormData，使用bytes而不是File
                    FormData formData = FormData.fromMap({
                      //
                      "file": MultipartFile.fromBytes(
                        bytes,
                        filename: image.name, // 设置文件名
                      ),
                    });
                    uploadAvatar(tag, formData);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  uploadAvatar(String tag, FormData fd) async {
    try {
      // 1. 包装一个FormData对象

      // 2. 调用上传接口
      var res = await http.post('/upload', data: fd);
      logger.i(res);
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败');
      // print(res);
      setState(() {
        _formData[tag] = res['data']['url'];
        ToastUtil.showSuccess('上传图片成功');
      });
    } catch (e) {
      ToastUtil.showError('上传图片失败');
    } finally {
      Navigator.pop(context);
    }
  }

  _submitForm() async {
    if (!Validate.validateName(_nameController.text)) {
      return;
    }
    // 使用校验工具 对手机号 和 用户名 进行校验
    if (!Validate.validatePhone(_mobileController.text)) {
      return;
    }
    _formData['name'] = _nameController.text;
    _formData['mobile'] = _mobileController.text;
    logger.i(_formData);
    if (_formData.containsKey('id')) {
      _formData.remove('status');
    }
    try{
      final res = await http.post('/room', data: _formData);

      String tag = widget.params.containsKey('id') ? '修改' : '添加';
      if (res['code'] != 10000) return ToastUtil.showError('$tag房屋失败!');
      ToastUtil.showSuccess('$tag房屋成功');
      Navigator.popUntil(context, (route) {
        print(route.settings.name);
        return route.settings.name == '/';
      });
    }catch(e){

    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // title: Text('添加房屋信息'),
         title: widget.params['id'] != null
          ? Text('修改房屋信息')
            : Text('添加房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.only(top: 10, bottom: 10),
        children: [
          // 房屋信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '房屋信息',
              style: TextStyle(
                color: Color.fromARGB(255, 97, 94, 94),
                fontSize: 16,
              ),
            ),
          ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(
              left: 10,
              right: 10,
              top: 15,
              bottom: 15,
            ),
            child: Text(
                '${_formData['point'] ?? ''}${_formData['building'] ?? ''}${_formData['room'] ?? ''}室',
            ),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '业主信息',
              style: TextStyle(
                color: Color.fromARGB(255, 97, 94, 94),
                fontSize: 16,
              ),
            ),
          ),
          // 业主姓名
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              controller: _nameController,
              maxLength: 15,
              decoration: const InputDecoration(
                labelText: '姓名',
                hintText: '请输入业主姓名',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
              inputFormatters: [LengthLimitingTextInputFormatter(10)],
            ),
          ),
          // 性别
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: Row(
              children: [
                const Text('性别', style: TextStyle(fontSize: 16)),
                const SizedBox(width: 20),
                Radio(
                  value: 1,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('男'),
                const SizedBox(width: 10),
                Radio(
                  value: 0,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('女'),
              ],
            ),
          ),
          // 业主手机号
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              controller: _mobileController,
              keyboardType: TextInputType.phone,
              maxLength: 11,
              decoration: const InputDecoration(
                labelText: '手机号',
                hintText: '请输入您的手机号',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
              inputFormatters: [LengthLimitingTextInputFormatter(11)],
            ),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '本人身份证照片',
              style: TextStyle(
                color: Color.fromARGB(255, 97, 94, 94),
                fontSize: 16,
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
            child: const Text(
              '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
              style: TextStyle(
                color: Color.fromARGB(255, 97, 94, 94),
                fontSize: 12,
              ),
            ),
          ),
          // 身份证正面
          Container(
            color: Colors.white,
            height: 320,
            padding: const EdgeInsets.all(10),
            child:
                _formData['idcardFrontUrl'] == ''
                    ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                    : _buildIdcardPhoto(
                      'idcardFrontUrl',
                      _formData['idcardFrontUrl'],
                    ),
          ),
          const SizedBox(height: 20),
          // 身份证反面
          Container(
            color: Colors.white,
            height: 320,
            padding: const EdgeInsets.all(10),
            child:
                _formData['idcardBackUrl'] == ''
                    ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                    : _buildIdcardPhoto(
                      'idcardBackUrl',
                      _formData['idcardBackUrl'],
                    ),
          ),
          const SizedBox(height: 20),
          // 提交审核
          Container(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                // TODO: 提交审核
                _submitForm();
              },
              child: const Column(
                children: [
                  SizedBox(height: 8),
                  Icon(Icons.exit_to_app),
                  Text('提交审核'),
                  SizedBox(height: 8),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
